<template>
  <div v-if="userDefineColumns && userDefineColumns.length >0 ">
    <el-row v-if="!onlyShow">
      <el-button size="small" @click="addDefaultLine">添加一行</el-button>
    </el-row>
    <el-table :data="list" style="width: 100%" :options="options" height="400" highlight-current-row ref="dynamicTable" :header-cell-style="{background: '#DCDFE6'}">
      <template v-if="userDefineColumns">
      <el-table-column  v-for="(item,index) in userDefineColumns" :prop="item.code" :label="item.name" :key="index">
        <template slot-scope="scope">
          <el-input v-model="scope.row[item.code]" v-if="scope.row.id == editId" size="small"></el-input>
          <span v-else>{{ scope.row[item.code] }}</span>
        </template>
      </el-table-column>
    </template>
      <el-table-column v-if="!onlyShow" label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="text" v-if="scope.row.id != editId && !scope.row.fixed" @click="changeHandler(scope.row)" size="small">编辑</el-button>
          <el-button type="text" v-if="scope.row.id != editId && !scope.row.fixed" @click="removeHandler(scope.row)" size="small">删除</el-button>
          <el-button type="text" v-if="scope.row.id == editId && !scope.row.fixed" @click="cancelHandler(scope.row)" size="small">取消</el-button>
          <el-button type="text" v-if="scope.row.id == editId && !scope.row.fixed" @click="saveHandler(scope.row)" size="small">保存</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script lang="ts">
import { Component,Emit, Prop, Vue,Ref,Watch } from 'vue-property-decorator';
@Component
export default class DynamicModel extends Vue {
 //用来产生动态列表头
  @Prop() userDefineColumns:any;
  //用来渲染设计数据
  @Prop() defaultList:any;
  //用来渲染填报数据
  @Prop() dataList:any;
  @Ref('dynamicTable') dynamicTable:any;

  @Prop({
    default(){
      return false;
    }
  }) onlyShow:any;

  @Prop({
    default: () => ({//表格样式参数
      stripe: false, // 是否为斑马纹 table
      loading: false, // 是否添加表格loading加载动画
      highlightCurrentRow: false, // 是否支持当前行高亮显示
      multipleSelect: false, // 是否支持列表项选中功能
      defaultSort: {
        prop: 'id',
        order: 'descending'
      },
      border: false,
      expand: false,
      expandColumn: 3,
      expandSize: '',
      align: 'center',//对齐方式
      index: false,//是否显示序号
    })
  }) 
  private options!: any;
  //表格内部数据
  public list: Array<any> = [];
  //用来编辑表格的ID
  editId = '';
  //编辑表格时旧的数据保存，取消时可以退回
  editData = {};

  //处理删除
  removeHandler(row:any) {
    this.list = this.list.filter(item => item.id !== row.id);
    this.editId = ''
  }
  //处理编辑
  cancelHandler(row:any) {
    if (row.id) {
      if(this.editData){
        for (let i in row) {
          row[i] = this.editData[i]
        }
      }
    }else{
      this.removeHandler(row);
    }
    this.editId = ''
  }
  //处理保存
  saveHandler(row:any) {
    row.id = "newAdd"+ Math.random() *2000000;
    this.editId = '';
    this.callBackDataHandler(this.list);
    
  }
  //点击编辑时候进入这里
  changeHandler(row) {
      if (this.list.some((item) => {
        return item.id == ''
      })) {
        this.$message({ message: '请先保存', type: 'warning' });
        return
      }
    this.editData = JSON.parse(JSON.stringify(row))    
    //把当前行数据存一份，取消的时候行数据还原
    this.editId = row.id
  }
  //添加一行默认数据
  addDefaultLine() {
    if (this.editId != '') {
      this.$message({ message: '请先保存', type: 'warning' }); return;
    }
    if (this.list.some((item) => { return item.id == '' })) {
      this.$message({ message: '请先保存', type: 'warning' });
      return;
    }
    const newModel = {'id':''};
    if(this.userDefineColumns){
      this.userDefineColumns.forEach((k:any) =>{
        newModel[k.code] = '';
      })
      this.list.push(newModel);
    }
  }
 
  //初始化表头数据
  initDefaultData(newVal:any){
    if(newVal){
      this.list =[];
      newVal.forEach((dt:any) =>{
        //表头是固定的所以不能增删改
        dt.fixed = true;
        this.list.push(dt);
      });
    }
    this.addDataList();
  }

  //添加默认数据
  addDataList(){
    if(this.list && this.list.length > 0){
      if(this.dataList){
        this.dataList.forEach((data:any)=>{
          const newModel = {'id':''};
          this.userDefineColumns.forEach((k:any) =>{
            newModel[k.code] = data[k.code];
          })
          this.list.push(newModel);
        });
      }
    }
  }
  addDynamicDataList(list){
    this.list.push(...list);
  }

  /**
   * 父组件用来收集数据
   * @param val 
   */
  @Emit('backHandler')
  @Emit('backHandler')
  callBackDataHandler(val:any) {
    const dt =  val.filter((item:any) => !item.fixed);
    return dt;
  }

  //监听数据变化
  @Watch('defaultList')
  onchangeDefaultList(newVal: any, oldVal: any){
    this.initDefaultData(newVal);
  }
  @Watch('dataList')
  onchangeDataList(newVal: any, oldVal: any){
    this.addDataList();
  }
  mounted(){
    this.initDefaultData(this.defaultList);
  }
}
</script>